最大最小值
python 里找 float 的最小值,float(‘-inf’),最大值,float(‘inf’)
找 int 的最大最小值
其它
class 里创建 helper 方法第一个参数传 self, 调用 self.helper()
python 的三元运算符,python 的 max 方法。
基础
概念
- Root: The node at the top of the tree
- Parent: When any node (except the root) has exactly one edge running upward to another node. The node above is called parent of the node.
- Child: Any node may have one or more lines running downward to other nodes. These nodes below the given node called its children.
- Edge: connection between one node to another.
- Leaf: A node that has no children is called a leaf. There can be only one root in a tree but there can be many leaves.
- Level: The level of a node is defined by 1 + the number of connections between the node and the root.
- Path: – a sequence of nodes and edges connecting a node with a descendant.
- Height of node – The height of a node is the number of edges on the longest downward path between that node and a leaf.
- Height of tree –The height of a tree is the number of edges on the longest downward path between the root and a leaf.
- Depth –The depth of a node is the number of edges from the node to the tree’s root node.
complexity
insertion, 平均 O(logN),左树找到 SPOT,右树找到 SPOT,一次砍一半,就是 O(logN)
deletion,平均情况 O(logN)多一些,先搜索到元素,O(logN),没找到就 end,找到,分 4 种,记录元素是 left 还是 right
- leaf parent 对应指针指到 null
- 仅有左边 child,parent 对应指针指到左 child,元素指针全部删除
- 仅有右边 child,parent 对应指针指到右 child,元素指针全部删除
- 有左右两个 child,先找 successor,就是右子树的最小严肃,从要删除的元素往下一路向左,找到最左元素,定为 successor,然后如果 successor 有右树,将其连到 parent 的左树上,successor 新的右树,连到被删除元素的右树上。
Binary search tree 二叉搜索树
二叉搜索树每个节点比其左子树元素大,比其右子树元素小。
The left subtree of a node contains only nodes with keys less than node’s key.
The right subtree of a node contains only nodes with keys greater than node’s key.
二叉搜索树的作用:保持元素顺序,相当于是一个排序好的 list,插入删除操作,比排序的 list 快,维护元素顺序或对元素排序时,非常适用。
Balanced binary tree 平衡树
树结构越接近一个链条,各操作就越像线性结构,就越失去了树结构独特的优势,所以引入了平衡树
遍历方法
- 深度优先(DFS)
先根(preorder),中根(inorder),后根(postorder) - 广度优先(BFS)
优先遍历完同层,是一个 queue 结构,先 dequeue 根节点 q,按照层序 enqueue 其 children,visit(q)然后 dequeue 根部新根节点。继续 enqueue,重复刀 dequeue 空为止。所有 node 都被 enqueue 和 dequeue 一遍,复杂度是 O(2n),即 O(n)
stack & DFS
先根(144.Binary Tree Preorder Traversal)
注意 conner case root==None 的时候返回的是[],不是 root(None)。
中根(94.Binary Tree Inorder Traversal)
|
|
后根(145.Binary Tree Postorder Traversal)
|
|
queue & BFS(102. Binary Tree Level Order Traversal)
Problem
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
遍历当前的 queue, 把每个 node value 存到 list,将每个 node 的 left 和 right node 存到 queue,遍历完后将当前 list 加进 result 里。
问题是怎么遍历当前 queue,通过纪录每个 layer(也就是 queue)的长度来实现。
corner case: root == None, return []
Time complexity: O(n),每个 node enqueue 一次,dequeue 一次
Space complexity: O(n),worst space,最后一次,满树,大概 O(n/2)
Solution
|
|
解题策略
Divide and conquer
树和图的很多问题,可以分解成子问题递归求解(divide and conquer),一般思路是综合节点本身,左子树,右子树三方的局部解得到全局解。
要注意的是,传节点的时候
- 设置出口,ending case,一般是 node==None;
- Recursive down
- Return up
- Current layer
构造递归的时候,可以 suppose all subtrees are handled.
特定路径的问题
关于寻找特定路径的问题,通常需要回溯思想,我们往往需要设计一个 helper function,传入当前节点和其它需要记录的参数。
树和其他数据结构的相互转换
树 –> 其它数据结构:树的遍历,合并局部解来得到全局解
其它数据结构 –> 树:递归将数据结构的两部分分别转换成子树,再合并。
寻找特定节点
此类题目通常会传入一个当前节点,要求找到与此节点具有一定关系的特定节点:例如前驱、后继、左/右兄弟等。
对于这类题目,首先可以了解一下常见特定节点的定义及性质。在存在指向父节点指针的情况下,通常可以由当前节点出发,向上倒推解决。如果节点没有父节点指针,一般需要从根节点出发向下搜索,搜索的过程就是DFS。
注意点
Error control:
- 确定 node.left, node.right 是否为 None,尤其是 leverl order traversal 中。
- connection between nodes 在原来的 tree 上更改箭头,这样更清楚要不要抛弃某些箭头。
例题
101. Symmetric Tree
Problem
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
Solution
|
|
156. Binary tree upside down
Problem
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
1
/ \
2 3
/ \
4 5
return the root of the binary tree [4,5,2,#,#,3,1].
4
/ \
5 2
/ \
3 1
Assumption: input tree is valid
Conner Case: Null root –> Null new root
Solution
Stack 解法
Time compexity: O(n)
Space complexity: O(n/2)
Recursive 解法
Identical subproblem, lower level first
通过 root.left 过渡到下一个子问题,从下往上
98. Valid binary search tree
Problem
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Solution
Inorder traversal
根据二叉搜索树的性质,我们知道二叉搜索树中序遍历之后是一个 sorted list,所以最直观的方法就是中序遍历存到一个 list,然后看它是不是 sorted。这样的空间复杂度是 O(N),时间复杂度由排序算法决定。
Global max
用 global max 能让空间复杂度变成 O(1)?这个还不知道。。
Range
分解子问题,每一个 node 都大于它的 left child 并且小于它的 right child。所以可以写一个 helper function,传入 (node, min, max) 来判断 node 在不在正确的区间里。主要问题如下:
- how to compare cross-layer
- how to get a valid range for each node
implementation: pass parameter top-to-bottom, helper(current_node,min,max)
注意小知识点,python 里找 float 的最小值,float(‘-inf’),最大值,float(‘inf’)
|
|
333. Largest BST Subtree
Problem
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Here’s an example:
10
/ \
5 15
/ \ \
1 8 7
The Largest BST Subtree in this case is the highlighted one.
The return value is the subtree’s size, which is 3.
Solution
|
|
298. Binary Tree Longest Consecutive Sequence
Problem
Given a binary tree, find the length of the longest consecutive sequence path.
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).
For example,
1
\
3
/ \
2 4
\
5
Longest consecutive sequence path is 3-4-5, so return 3.
2
\
3
/
2
/
1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
直接想到的是,preorder 遍历,得到 list,用 count 更新 current max。然而这是有问题的!以 example 为例,遍历后的 list 是 [1,3,2,4,5],它把 2,4 连起来了,但是 2,4 属于不同的分支,所以不能这么做。
换一种思路,用 recursion 的方法,左子树的 max length, 右子树的 max length,和本身目前的 max length,求最大值。
第一个传进去的是什么?float(‘inf’)
Solution
|
|
待补充
trie or prefix tree,full binary tree,complete binary tree,heap
222. Count Complete Tree Nodes
Problem
Given a complete binary tree, count the number of nodes.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Solution
Time complexity: O(h^2)
270. Closest Binary Search Tree Value
Problem
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.
Note:
Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Solution
|
|
272. Closest Binary Search Tree Value II
Problem
Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
Solution
|
|
366. Find Leaves of Binary Tree
Problem
Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Example:
Given binary tree
1
/ \
2 3
/ \
4 5
Returns [4, 5, 3], [2], [1].
Explanation:
1.Removing the leaves [4, 5, 3] would result in this tree:
1
/
2
2.Now removing the leaf [2] would result in this tree:
1
3.Now removing the leaf [1] would result in the empty tree:
[]
Returns [4, 5, 3], [2], [1].
Solution
|
|
307. Range Sum Query - Mutable (Binary indexed tree)
Problem
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Example:
Given nums = [1, 3, 5]
sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
Solution
|
|